/**
 * GraphPanel.java
 * 
 * Wrapper for the JFreeChart Library. Allows for concurrent updating of a chart and
 * allows for a maximum of two plots to be displayed on the chart.
 * 
 * TODO: Fix concurrency issues
 */
package com.swin.energy;

import java.awt.BorderLayout;
import java.awt.Color;

import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.AxisLocation;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;

public class GraphPanel extends JPanel {

	private JFreeChart chart;
	private XYSeries series = new XYSeries("Actual Data");
	private XYSeries series2 = new XYSeries("Estimate");
	
	private XYSeriesCollection dataset;
	private ChartPanel chartPanel;
	
	private String title;
	private String xLabel;
	private String yLabel;
	
	public GraphPanel(String title, String xLabel, String yLabel) {
		this.title = title;
		this.xLabel = xLabel;
		this.yLabel = yLabel;
		
		dataset = new XYSeriesCollection();
		dataset.addSeries(series);
		dataset.addSeries(series2);
		chart = createNewChart();
		chartPanel = new ChartPanel(chart);
		chartPanel.setBorder(new EmptyBorder(0, 50, 0, 20));
		this.setBorder(new EmptyBorder(0, 20, 0, 20));		
		this.add(chartPanel, BorderLayout.CENTER);
		this.validate();
	}
	
	private JFreeChart createNewChart() {
		
		JFreeChart tempChart = ChartFactory.createXYLineChart(
				this.title, // chart title
				this.xLabel, // domain axis label
				this.yLabel, // range axis label
				dataset, // data
				PlotOrientation.VERTICAL, 
				true, // include legend
				true, false);
		tempChart.setBackgroundPaint(Color.white);
		final XYPlot plot = tempChart.getXYPlot();
		plot.setDomainAxisLocation(AxisLocation.BOTTOM_OR_LEFT);
		plot.setOutlinePaint(Color.black);
		return tempChart;
	}

	private static final long serialVersionUID = -824926211328651694L;

	public void clearData() {
		this.series.clear();
		this.series2.clear();
	}
	
	public synchronized void updateChart(double x, double actual, Double estimate) {
		series.add(x, actual);
		if (estimate != null) {
			series2.add(x, estimate);
		}
		this.revalidate();
		this.chart = createNewChart();
		this.repaint();
		chartPanel = new ChartPanel(chart);
		this.add(chartPanel, BorderLayout.CENTER);
		this.validate();
	}

}
